<template>
	<div class="layout-padding fillings-container" v-loading="loading">
		<HyTable
			:tableConfig="tableConfig"
			:tableColumns="tableColumns"
			:searchFields="searchFields"
			:searchConfig="searchConfig"
			:searchDefault="searchDefault"
			ref="hyTableRef"
			:buttonConfig="{
				span: 4,
				offset: 1,
			}"
		>
			<template #tableHeader>
				<el-button type="primary" @click="addFilings" icon="Plus">新建</el-button>
				<el-button plain icon="download" @click="handleExport">导出</el-button>
			</template>
			<template #stateSlot="{ row, column }">
				<!-- <el-tag type="primary" v-if="row.country_approve_status == 2">{{ formatStatus(row.country_approve_status) }}</el-tag>
				<el-tag type="danger" v-else-if="row.country_approve_status == 4">{{ formatStatus(row.country_approve_status) }}</el-tag>
				<el-tag type="success" v-else-if="row.country_approve_status == 3">{{ formatStatus(row.country_approve_status) }}</el-tag>
				<el-tag type="danger" v-else>{{ formatStatus(row.country_approve_status) }}</el-tag> -->
				<el-tag :class="setColor(row.country_approve_status)">{{ formatStatus(row.country_approve_status) }}</el-tag>
			</template>
			<template #operation>
				<el-table-column fixed="right" label="操作" width="130">
					<template #default="{ row }">
						<div class="table-operation">
							<el-button text type="primary" icon="View" @click="showDetails(row)">查看</el-button>
							<el-dropdown v-if="checkDropList(row)">
								<span class="el-dropdown-link">
									更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
								</span>
								<template #dropdown>
									<el-dropdown-menu>
										<div v-for="item in dropdownList" :key="item">
											<el-dropdown-item @click="() => clickDropItem(row, item)" v-if="checkRule(row, item)">
												<span
													class="align-center"
													:class="item == '编辑' ? 'edit-color' : item == '删除' ? 'del-color' : item == '撤销' ? 'back-color' : 'default-color'"
												>
													<el-icon>
														<Edit v-if="item == '编辑'" />
														<Delete v-else-if="item == '删除'" />
														<Reading v-else-if="item == '撤销'" />
														<Document v-else />
													</el-icon>
													{{ item }}
												</span>
											</el-dropdown-item>
										</div>
									</el-dropdown-menu>
								</template>
							</el-dropdown>
						</div>
					</template>
				</el-table-column>
			</template>
		</HyTable>

		<SendBack ref="sendBackRef" :boxConfig="{ title: '撤回确认', width: '60%' }" @submitPass="submitPass"></SendBack>
	</div>
</template>

<script lang="ts">
import { defineComponent, ref, toRaw } from 'vue';
import { useRouter } from 'vue-router';
import { getCountyDeclareList, delAppDeclare, returnTask, exportExcel, isExsitById } from '/@/api/areaDigital';
import { revocation } from '@cqdcg/admin/views/flow/task/revocation';
import { cancel } from '@cqdcg/admin/views/flow/task/cancel';
import SendBack from '@cqdcg/admin/views/flow/task/sendBack';
import HyTable from '/@/components/HyTable/components/TableLayout/default.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useDict } from '/@/hooks/dict';
import { Session } from '/@/utils/storage';
import { handleBlobFile } from '/@/utils/other';

export default defineComponent({
	name: 'index',
	components: { HyTable, SendBack },
	setup() {
		const router = useRouter();
		const tableColumns = computed(() => {
			return [
				{ prop: 'app_code', label: '数字化应用编号' },
				{ prop: 'app_name', label: '数字化应用名称' },
				{ prop: 'county_name_name', label: '区县名称' },
				{ prop: 'county_responsible_dept_name', label: '区县责任部门' },
				{ prop: 'county_lead_dept_name', label: '市级牵头部门' },
				{ prop: 'create_time', label: '提交时间' },
				{
					prop: 'country_approve_status_name',
					label: '状态',
					slot: 'stateSlot',
					fixed: 'right',
					width: 160,
				},
			];
		});
		const loading = ref(false);
		const tableConfig = ref({
			request: getCountyDeclareList,
			showSearch: true,
			isCostomTop: false,
			indexFixed: true,
			title: '数字化应用备案申报',
			defaultData: [],
		});
		const { country_approve_status: AREA_STATUS } = useDict('country_approve_status');
		// 配置搜索
		const searchFields = ref({
			countyNameName: {
				type: 'input',
				label: '区县名称',
				span: 8,
				placeholder: '请输入区县名称',
			},
			countryApproveStatus: {
				type: 'select',
				label: '状态',
				span: 8,
				placeholder: '请选择状态',
				options: AREA_STATUS,
			},
			timeArr: {
				type: 'date',
				span: 8,
				picker: 'datetimerange',
				label: '提交时间',
			},
		});
		const searchDefault = ref({
			selectType: 1,
		});
		const searchConfig = computed(() => {
			return {
				labelWidth: '120px',
				span: 6,
				offset: 0,
				type: 'search',
				title: '数字化应用备案申报',
				show: true,
			};
		});
		const statusMap: any = {
			'1': ['查看', '申报', '编辑', '删除'], //待申报
			'2': ['查看', '撤销'], //申报中   （下级节点未审核）
			'3': ['查看'], //已通过
			'4': ['查看', '重新发起'], //未通过 '申报', '编辑', '删除'
		};
		const dropdownList = ref(['申报', '编辑', '删除', '撤销', '重新发起']); //（下级节点未审核）
		const hyTableRef = ref();
		const sendBackRef = ref(null);
		async function showDetails(row) {
			console.log(row);
			const result = await checkData(row.declare_id);
			if (result) {
				router.push({
					name: '查看',
					query: {
						id: row.declare_id,
						processInstanceId: row.process_instance_id,
						nodeId: row.node_id,
						taskId: row.task_id,
						approveStatus: row.approve_status,
						pageType: 1,
						title: '数字化应用备案详情',
					},
				});
			}
		}
		function addFilings() {
			router.push({
				name: '新增备案',
			});
		}
		async function clickDropItem(row, type) {
			console.log(row, type);
			const result = await checkData(row.declare_id, type == '撤销' ? 1 : '');
			if (result) {
				if (type == '删除') {
					ElMessageBox.confirm('删除后将无法恢复', '你确定要删除吗？', {
						confirmButtonText: '确认',
						cancelButtonText: '取消',
						confirmButtonClass: 'el-button--danger',
						type: 'warning',
					})
						.then(() => {
							loading.value = true;
							delAppDeclare([row.declare_id])
								.then((res) => {
									if (res.ok) {
										hyTableRef.value.getTableData();
										ElMessage({
											type: 'success',
											message: '操作成功',
										});
									} else {
										ElMessage({
											type: 'error',
											message: res.msg,
										});
									}
								})
								.finally(() => {
									loading.value = false;
								});
						})
						.catch(() => {});
				}
				if (type == '申报' || type == '编辑' || type == '重新发起') {
					router.push({
						name: '新增备案',
						query: {
							tagsViewName: type == '重新发起' ? '新增备案' : '编辑备案',
							processInstanceId: row.process_instance_id,
							nodeId: row.node_id,
							taskId: row.task_id,
							appCode: row.app_code,
							id: row.declare_id,
						},
					});
				}
				if (type == '撤销') {
					// ElMessageBox.confirm('确定撤销吗？', '撤销确认', {
					// 	confirmButtonText: '确定',
					// 	cancelButtonText: '取消',
					// }).then(() => {
					// 	loading.value = true;
					// 	returnTask({
					// 		processInstanceId: row.process_instance_id,
					// 	})
					// 		.then((res) => {
					// 			if (res.ok) {
					// 				ElMessage.success('操作成功');
					// 				hyTableRef.value.getTableData();
					// 			} else {
					// 				ElMessage.error(res.msg);
					// 			}
					// 		})
					// 		.finally(() => {
					// 			loading.value = false;
					// 		});
					// });
					//撤销
					// let data = {
					// 	processInstanceId: row.process_instance_id,
					// };
					// cancel(data)
					// 	.then((res: any) => {
					// 		hyTableRef.value.getTableData();
					// 	})
					// 	.catch((err: any) => {
					// 		console.log('取消弹框和失败回调');
					// 	})
					// 	.finally(() => {
					// 		loading.value = false;
					// 	});
					//退回

					loading.value = false;
					let obj = {
						processInstanceId: row.process_instance_id,
					};

					// sendBackRef.value.handle({
					// 	processInstanceId: row.process_instance_id,
					// 	paramMap: {},
					// });
					revocation(obj)
						.then((res: any) => {
							console.log('撤回接口成功回调');
							submitPass();
						})
						.catch((err: any) => {
							console.log('取消弹框和失败回调');
						});
				}
			}
		}
		const submitPass = () => {
			hyTableRef.value.getTableData();
		};
		type checkParams = {
			declareId: string;
			checkFlag?: number | string;
		};
		function checkData(declareId: string, flag?: number | string) {
			//判断数据是否存在
			if (!loading.value) {
				loading.value = true;
			}
			let params: checkParams = { declareId: declareId };
			if (flag) {
				params['checkFlag'] = flag;
			}
			return new Promise((resolve) => {
				isExsitById(params).then((res) => {
					if (res.ok) {
						if (res.data) {
							resolve(true);
						} else {
							loading.value = false;
							ElMessage.error('该数据已被删除');
							hyTableRef.value.getTableData();
						}
					} else {
						loading.value = false;
						ElMessage.error(res.msg);
						resolve(false);
					}
				});
			});
		}
		function checkRule(row: any, type: any) {
			return statusMap[row.country_approve_status]?.includes(type);
		}
		function checkDropList(row) {
			if (row.country_approve_status == 1) {
				return true;
			} else if (row.country_approve_status == 2) {
				// return true;
				if (row.county_push_status == 1) {
					//待推送
					return true;
				} else {
					return false;
				}
			} else if (row.country_approve_status == 3) {
				return false;
			} else {
				return true;
			}
		}
		function formatStatus(val) {
			const rowArr = AREA_STATUS.value.filter((item) => item.value == val);
			return rowArr.length && rowArr[0].label;
		}
		//导出
		function handleExport() {
			let params = hyTableRef.value.getSearchData();
			params['beginTime'] = params['timeArr'] ? params['timeArr'][0] : undefined;
			params['endTime'] = params['timeArr'] ? params['timeArr'][1] : undefined;
			delete params.timeArr;
			console.log(params);
			loading.value = true;
			exportExcel(params)
				.then((res) => {
					loading.value = false;
					handleBlobFile(res, '数字化应用备案申报.xlsx');
				})
				.catch(() => {
					loading.value = false;
				});
		}
		//设置颜色
		function setColor(type: string) {
			switch (type) {
				case '1':
					return 'start-tag'; //待申报
				case '2':
					return 'wait-tag'; //申报中
				case '4':
					return 'refuse-tag'; //未通过
				case '3':
					return 'agree-tag'; //已通过
				default:
					break;
			}
		}
		return {
			loading,
			hyTableRef,
			sendBackRef,
			tableColumns,
			tableConfig,
			searchFields,
			searchDefault,
			searchConfig,
			statusMap,
			dropdownList,
			showDetails,
			addFilings,
			clickDropItem,
			checkDropList,
			checkRule,
			formatStatus,
			handleExport,
			setColor,
			submitPass,
		};
	},
});
</script>

<style scoped lang="scss">
.fillings-container {
	height: auto;
	.table-operation {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 10px;
		.el-dropdown-link {
			color: #2e5cf6;
			line-height: 32px;
		}
	}
}
.align-center {
	display: flex;
	align-items: center;
}
.edit-color {
	color: #52c41a;
}
.del-color {
	color: #f74e56;
}
.back-color {
	color: #f5222d;
}
.default-color {
	color: var(--el-color-primary);
}
</style>
